package com.example.pufang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.PageParamRequest;
import com.example.pufang.mapper.FeedbackMapper;
import com.example.pufang.pojo.Feedback;
import com.example.pufang.pojo.SystemMessage;
import com.example.pufang.pojo.User;
import com.example.pufang.service.FeedbackService;
import com.example.pufang.service.SystemMessageService;
import com.example.pufang.vo.FeedbackAdminListVo;
import com.example.pufang.vo.FeedbackFrontListVo;
import com.example.pufang.vo.PageListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private SystemMessageService systemMessageService;

    @Value("${img.path}")
    private String imgPath;

    @Override
    public List<FeedbackFrontListVo> getFeedbackList(PageParamRequest pageParamRequest, User user) {

        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotNull(user), Feedback::getUserId, user.getId())
                .orderByDesc(Feedback::getCreateTime);

        Page<Feedback> feedbackPage = new Page<>(pageParamRequest.getPage(), pageParamRequest.getLimit());
        IPage<Feedback> feedbackIPage = feedbackMapper.selectPage(feedbackPage , wrapper);

        List<FeedbackFrontListVo> responseList = feedbackIPage.getRecords().stream().map(e -> {
            FeedbackFrontListVo feedbackListVo = new FeedbackFrontListVo();
            BeanUtils.copyProperties(e, feedbackListVo);
            return feedbackListVo;
        }).collect(Collectors.toList());

        return responseList;
    }


    @Override
    public PageListVo getListByPage(PageParamRequest pageParamRequest, String searchName, String searchRealName,
                                    String searchPhone) {

        PageListVo pageListVo = new PageListVo();

        int start = (pageParamRequest.getPage()-1)* pageParamRequest.getLimit();
        int limit = pageParamRequest.getLimit();

        List<FeedbackAdminListVo> feedbackList = baseMapper.getListByPage(start, limit, searchName, searchRealName, searchPhone);

        // 将图片url添加地址
        try {
            feedbackList = feedbackList.stream().map(e -> {
                if (StringUtils.isNotBlank(e.getImg())) {
                    List<String> imgList = (List<String>) JSONArray.parse(e.getImg());
                    ArrayList<String> imgListResult = new ArrayList<>();
                    imgList.forEach((imgUrl) -> {
                        imgListResult.add(imgPath + imgUrl);
                    });
                    e.setImg(JSON.toJSONString(imgListResult));
                }
                return e;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 获取总数
        Long total = baseMapper.count(searchName, searchRealName, searchPhone);

        // 获取总页数
        long l = total % pageParamRequest.getLimit();
        long totalPage = 0;
        if (l > 0) {
            totalPage = Math.floorDiv(total, pageParamRequest.getLimit()) + 1;
        } else {
            totalPage = Math.floorDiv(total, pageParamRequest.getLimit());
        }

        pageListVo.setPage((long) pageParamRequest.getPage())
                .setSize((long) pageParamRequest.getLimit())
                .setList(JSONObject.toJSONString(feedbackList))
                .setTotal(total)
                .setTotalPage(totalPage);

        return pageListVo;
    }

    @Override
    public Boolean reply(Feedback feedback) {

        Feedback selectByIdFeedback = baseMapper.selectById(feedback.getId());
        selectByIdFeedback.setReply(feedback.getReply());

        // 保存到系统消息
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setAdminId(-1)
                .setMessage("您提交的关于\"" + selectByIdFeedback.getTitle()
                        + "\"的反馈，客服已回复，请前往个人中心查看。")
                .setReceiverId(selectByIdFeedback.getUserId());

        systemMessageService.save(systemMessage);

        return this.updateById(selectByIdFeedback);
    }
}
